import os

from pip._vendor.distlib.compat import raw_input
'''
文件合并
'''

class concatfile:
    def __init__(self, file_path, except_filename, lastcode):
        self.file_path = file_path
        self.except_filename = except_filename
        self.lastcode = lastcode

    # 将sql或者文本合并起来
    def concat(self):
        for dirpath, dirnames, filenames in os.walk(self.file_path):
            for filename in filenames:
                try:
                    if filename == self.except_filename or not filename.__contains__(self.lastcode):
                        continue
                    inputfilename = dirpath.replace("\\", "/") + '/' + filename
                    with open(dirpath.replace("\\", "/") + '/' + self.except_filename, "a+", encoding="utf-8") as ff:
                        ff.write("\n" + "-- ----------------------------" + "\n")
                        ff.write("-- " + filename + "\n")
                        ff.write("-- ----------------------------" + "\n")
                        ff.write(open(inputfilename, encoding="utf-8").read())
                        print("concatfile success:" + inputfilename + " to " + self.except_filename)

                except FileExistsError as f:
                    print(f)
                    continue


if __name__ == "__main__":
    url = raw_input("请输入需要合并的文件所在文件夹路径:")
    url = url.replace("\\", "/")
    print("输入的文件夹路径为:" + url)
    except_filename = raw_input("请输入合并后文件名:")
    except_filename = except_filename.replace("\\", "/")
    print("合并后文件名:" + except_filename)
    lastcode = raw_input("请输入需要合并的文件的格式，例如：.sql \n")
    print("需要合并的文件的格式:" + except_filename)
    if os.path.exists(url + "/" + except_filename):
        os.remove(url + "/" + except_filename)
    cf = concatfile(url, except_filename, lastcode)
    cf.concat()
    i = "N"
    while i != "Y":
        i = input("按任意键退出")
        break
